import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by lanouhn on 17/7/18.
 */
public class CatchImg {
    //图片网址来源
    private static final String URL = "http://http://www.yoka.com/dna/222/117/index.html";
    //编码
    private static final String Encoding = "utf-8";
    //获取img标签正则表达式
    private  static final  String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
    //获取src路径的正则
    private  static final String IMGSRC_REG = "http:\"?(.*?)(\"|>|\\s+)";

    public static void main(String [] args) throws Exception{

        CatchImg cm = new CatchImg();
        String HTML = cm.getHTML(URL);
//        System.out.println(HTML);//没有结果出来，暂定程序增长进行
        List<String> imgUrl = cm.getImageUrl(HTML);
        List<String> imgSrc = cm.getImageSrc(imgUrl);
        cm.Download(imgSrc);
    }
    /*
     *获取HTML内容
     *@param url
     *@return
     *@throws Exception
     */
     private  String getHTML(String url) throws Exception{
        URL uri = new URL(url);
         URLConnection connection = uri.openConnection();
         InputStream in = connection.getInputStream();
         byte[] buf = new byte[1024];
         int length = 0;
         StringBuffer sb = new StringBuffer();
         while((length = in.read(buf,0,buf.length)) > 0){
             sb.append(new String(buf, Encoding));//设置获取的HTML内容的编码格式
         }
         in.close();
         return sb.toString();
     }

     /*
     *获取其中的ImageUrl地址
     * @param HTML
     * @return
     *
      */
     private List<String> getImageUrl(String HTML){
         Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);
         List<String> listImgUrl = new ArrayList<String>();
         while (matcher.find()) {
             listImgUrl.add(matcher.group());
         }
         return listImgUrl;
     }
     /*
      *获取imgsrc地址
      *
      * @param listImgUrl
      * @return
      *
      */
     private List<String> getImageSrc(List<String> listImageUrl) {
         List<String> listImgSrc = new ArrayList<String>();
         for (String image: listImageUrl) {
             Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);
             while (matcher.find()){
                 listImgSrc.add(matcher.group().substring(0,matcher.group().length() - 1));
             }
         }
         return listImgSrc;

     }
    private void Download (List<String> listImgSrc) throws Exception {
         try {
             for (String url: listImgSrc){
                 String imgName = url.substring(url.lastIndexOf("/") +1, url.length());
                 //构造URL
                 URL uri = new URL(url);
                 //打开连接
                 URLConnection con = uri.openConnection();
                 //这只请求时间5s
                 con.setConnectTimeout(5000);
                 //输入流
                 InputStream in = con.getInputStream();

                 //1k的数据缓冲
                 byte[] bs = new byte[1024];
                 //读取到的数据长度
                 int len;

                 //设置文件存储路径
                 String path = "/Users/lanouhn/Desktop/image/";
                 //输出的文件流
                 File fs = new File(path);

                 if(!fs.exists()){
                     fs.mkdirs();
                 }
                 OutputStream os = new FileOutputStream(fs.getPath() + "/" + imgName);
                 while ((len = in.read(bs)) != -1) {
                     os.write(bs, 0, len);
                 }

                 os.close();
                 in.close();
//                 String imgName = url.substring(url.lastIndexOf("/") +1, url.length());
//                 URL uri = new URL(url);
//                 InputStream in = uri.openStream();
//                 FileOutputStream fo = new FileOutputStream(new File(imgName));
//                 byte[] buf = new byte[1024];
//                 int length = 0;
//
//                 //输出文件流
//                 String path = "/Users/lanouhn/Desktop/image";
//                 File sf = new File(path);
//                 if(!sf.exists()){
//                     sf.mkdirs();
//                 }
////                 FileOutputStream  fo = new FileOutputStream(sf.getPath() + "/" + imgName);
//
//                 System.out.println("开始下载");
//                 while ((length = in.read(buf,0,buf.length)) != -1){
//                     fo.write(buf, 0, length);
//                 }
//                 //完成
//                 fo.close();
//                 in.close();
//                 System.out.println("下载成功!");
             }
         } catch (Exception e) {
             System.out.println("下载失败");
         }

    }
}
